﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using nwrole.toolbox.sync.client;
using nwrole.toolbox.sync.entity;
using nwrole.toolbox.sync.web.Models;
using nwrole.toolbox.sync.web.Utils;

namespace nwrole.toolbox.sync.web.Controllers
{
    public class DefaultController : Controller
    {
        private static int SyncInstanceId = 1; // Temp hardcoded, should be specified from a dropdown on the website

        public ActionResult Show(long id)
        {
            //var e = (new SyncEntityDemoRepository()).GetSyncEntity();

            SyncSourceServiceClient client = GetSourceServiceClient();
            var e = client.GetEntityById(id);
            return View(e);
        }

        [HttpPost]
        public ActionResult Show(SyncEntity model)
        {
            SyncSourceServiceClient client = GetSourceServiceClient();

            var e = client.GetEntityById(model.Id);
            e.SortIndex = model.SortIndex;
            e.DestinationTableName = model.DestinationTableName;
            e.TargetTableName = model.TargetTableName;
            e.SourceInsertedColumnName = model.SourceInsertedColumnName;
            e.SourceUpdatedColumnName = model.SourceUpdatedColumnName;
            e.SourceFilter = model.SourceFilter;
            e.DestinationSyncCompleteSPName = model.DestinationSyncCompleteSPName;
            e.SourceSyncStartSPName = model.SourceSyncStartSPName;
            e.SourceTimestampColumnName = model.SourceTimestampColumnName;

            if (!string.IsNullOrEmpty(e.TargetTableName) && string.IsNullOrEmpty(e.DestinationSyncCompleteSPName))
                e.DestinationSyncCompleteSPName = "INT_Import_" + e.Name;

            client.Update(e);

            return Show(model.Id);
        }

        [HttpPost]
        public ActionResult Status()
        {
            SyncSourceServiceClient client = GetSourceServiceClient();

            StatusViewModel viewModel = new StatusViewModel();
            viewModel.DeployStatus = client.GetDeployStatus();
            viewModel.Version = client.GetSettingStringValue("Version");
            
            return View();
        }

        public ActionResult SchemaShow(long id, short type)
        {
            //var e = (new SyncEntityDemoRepository()).GetSyncEntity();

            SyncSourceServiceClient client = GetSourceServiceClient();
            var e = client.GetSchemaEntity(id, type);
            return View(e);
        }

        public ActionResult ToggleSyncEnabled(long id)
        {
            SyncSourceServiceClient client = GetSourceServiceClient();
            var result = client.ToggleSyncEnabled(id);
            return Json(new
            {
                newValue = result,
                success = true
            }, JsonRequestBehavior.AllowGet);

            /*var val = SyncEntityColumn.ToggleSyncEnabled(id);
            return Json(new
            {
                newValue = val,
                success = true
            }, JsonRequestBehavior.AllowGet);*/
        }

        public ActionResult ToggleSyncMode(long id)
        {
            SyncSourceServiceClient client = GetSourceServiceClient();
            var result = client.ToggleSyncMode(id);
            return Json(new
            {
                newValue = result.ToString(),
                success = true
            }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult SyncAllSyncEntities(int id)
        {
            /*string instanceStr = Request["instance"];
            int instanceId = 1;
            if (!string.IsNullOrEmpty(instanceStr))
                instanceId = int.Parse(instanceStr);*/

            SyncSourceServiceClient client = GetSourceServiceClient();
            //client.SyncAllSyncEntities();

            if(client.StartFullSync(id))
            {
                /*while (client.SyncNextEntity(id))
                {
                }*/
                new Thread(InternallFullSync).Start(id);
            }

            return Json(new
            {
                newValue = 1,
                success = true
            }, JsonRequestBehavior.AllowGet);
        }

        private void InternallFullSync(object id)
        {
            int instanceId = (int) id;

            SyncSourceServiceClient client = GetSourceServiceClient();
            while(client.SyncNextEntity(instanceId))
            {
            }
        }

        /*public ActionResult SyncAllSyncEntities()
        {
            Thread thread = new Thread(InternalSyncAll);
            thread.Start();

            return Json(new
            {
                newValue = 1,
                success = true
            }, JsonRequestBehavior.AllowGet);
        }

        private void InternalSyncAll()
        {
            SyncSourceServiceClient client = GetSourceServiceClient();
            client.SyncAllSyncEntities();
        }*/

        public ActionResult SyncSyncEntity(long id)
        {
            SyncSourceServiceClient client = GetSourceServiceClient();
            client.SyncSyncEntity(id);

            return Json(new
            {
                newValue = 1,
                success = true
            }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult ImportSchema(long id, short type)
        {
            SyncSourceServiceClient client = GetSourceServiceClient();
            client.ImportSchema(SyncInstanceId, id, type);

            return Json(new
            {
                newValue = 1,
                success = true
            }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult DeploySource(long id)
        {
            SyncSourceServiceClient client = GetSourceServiceClient();
            client.DeploySource(id);

            return Json(new
            {
                newValue = 1,
                success = true
            }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult DeployDestination(long id)
        {
            SyncSourceServiceClient srcClient = GetSourceServiceClient();
            //srcClient.DeployDestination(id);
            SyncEntity syncEntity = srcClient.GetEntityById(id);

            SyncDestinationServiceClient destClient = GetDestinationServiceClient();
            if (destClient.DeployDestination(syncEntity))
            {
                syncEntity.DeployDestinationDat = DateTime.Now;
                srcClient.Update(syncEntity);
            } 

            return Json(new
            {
                newValue = 1,
                success = true
            }, JsonRequestBehavior.AllowGet);
        }


        public ActionResult DeleteSyncEntity(long id)
        {
            SyncSourceServiceClient client = GetSourceServiceClient();
            client.DeleteSyncEntity(id);

            return Json(new
            {
                newValue = 1,
                success = true
            }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult DeploySourceEnvironment()
        {
            SyncSourceServiceClient client = GetSourceServiceClient();
            client.DeploySourceEnvironment();

            return Json(new
            {
                newValue = 1,
                success = true
            }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult DeployDestEnvironment()
        {
            SyncDestinationServiceClient destClient = GetDestinationServiceClient();
            destClient.DeployDestEnvironment();

            return Json(new
            {
                newValue = 1,
                success = true
            }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult ToggleColumnSyncEnabled(long id)
        {
            SyncSourceServiceClient client = GetSourceServiceClient();
            var result = client.ToggleSyncColumnEnabled(id);
            return Json(new
            {
                newValue = result,
                success = true
            }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult ToggleAllColumnSyncEnabled(long id)
        {
            SyncSourceServiceClient client = GetSourceServiceClient();
            client.ToggleAllSyncColumnEnabled(id);
            return Json(new
            {
                success = true
            }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult DemoToggleColumnSyncEnabled(long id)
        {
            var val = SyncEntityColumn.ToggleSyncEnabled(id * 100);
            return Json(new
            {
                newValue = val,
                success = true
            }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Index()
        {
            SyncSourceServiceClient client = GetSourceServiceClient();
            if (client.GetDeployStatus() == 0)
                return RedirectToAction("Status");

            string instanceStr = Request["instance"];
            int instanceId = SyncInstanceId;
            if (!string.IsNullOrEmpty(instanceStr))
                instanceId = int.Parse(instanceStr);

            var list = client.GetEntities(instanceId);

            if (list == null)
                list = new List<SyncEntity>(); // Create an empty list for the view's sake

            ViewBag.InstanceId = instanceId;

            // var list = (new SyncEntityDemoRepository()).GetSyncEntityList();
            return View(list);
        }

        public ActionResult SchemaIndex(int page = 0, int pagesize = 1500)
        {
            SyncSourceServiceClient client = GetSourceServiceClient();
            var list = client.GetSchemaEntities(page, pagesize);

            return View(list);
        }

        public ActionResult FailedMessages()
        {
            SyncDestinationServiceClient destClient = GetDestinationServiceClient();
            var list = destClient.GetFailedMessages();
            return View(list);
        }

        public ActionResult FailedMessageRows(long id)
        {
            SyncDestinationServiceClient destClient = GetDestinationServiceClient();
            ViewBag.Message = destClient.GetMessage(id);
            var list = destClient.GetFailedMessageRows(id);
            return View(list);
        }

        private SyncSourceServiceClient GetSourceServiceClient()
        {
            /*bool runningSyncSourceLocal;
            if (!bool.TryParse(ConfigurationManager.AppSettings["RunningSyncSourceLocal"], out runningSyncSourceLocal))
                runningSyncSourceLocal = false;

            if (runningSyncSourceLocal)
            {
                string localServicePath = ConfigurationManager.AppSettings["SyncSourceLocalServicePath"];
                return new SyncSourceServiceClient(localServicePath);
            }

            string sbServiceNamespace = ConfigurationManager.AppSettings["SyncSourceSBServiceNamespace"];
            string sbServicePath = ConfigurationManager.AppSettings["SyncSourceSBServicePath"];
            string sbIssuerName = ConfigurationManager.AppSettings["SyncSourceSBIssuerName"];
            string sbIssuerSecret = ConfigurationManager.AppSettings["SyncSourceSBIssuerSecret"];

            return new SyncSourceServiceClient(sbServiceNamespace, sbServicePath, sbIssuerName, sbIssuerSecret);*/

            return new SyncSourceServiceClient(SiteSettings.SyncSourceConnInfo);
        }

        private SyncDestinationServiceClient GetDestinationServiceClient()
        {
            return new SyncDestinationServiceClient(SiteSettings.SyncDestinationConnInfo);
        }

    }
}
